package com.black.cat.seed.controller.login;


import com.black.cat.seed.common.ApiResponse;
import com.black.cat.seed.common.Status;
import com.black.cat.seed.dto.LoginRequest;
import com.black.cat.seed.exception.SecurityException;
import com.black.cat.seed.utils.JwtUtil;
import com.black.cat.seed.utils.SecurityUtil;
import com.black.cat.seed.vo.JwtResponse;
import com.black.cat.seed.vo.UserPrincipal;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * <p>
 * 认证 Controller，包括用户注册，用户登录请求
 * </p>
 *  @author blackcat
 *  @since 2020-07-21
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 登录
     */
    @PostMapping("/login")
    public ApiResponse login(@Valid @RequestBody LoginRequest loginRequest) {
        Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(loginRequest.getUsernameOrEmailOrPhone(), loginRequest.getPassword()));

        SecurityContextHolder.getContext()
                .setAuthentication(authentication);

        String jwt = jwtUtil.createJWT(authentication,loginRequest.getRememberMe());
        return ApiResponse.ofSuccess(new JwtResponse(jwt));
    }

    @PostMapping("/logout")
    public ApiResponse logout(HttpServletRequest request) {
        try {
            // 设置JWT过期
            jwtUtil.invalidateJWT(request);
        } catch (SecurityException e ){
            throw new SecurityException(Status.UNAUTHORIZED);
        }
        return ApiResponse.ofStatus(Status.LOGOUT);
    }


    @ApiOperation(value = "根据token获取用户详情")
    @GetMapping(value = "/getUserDetails")
    public ApiResponse<UserPrincipal> getUserDetails() {
        UserPrincipal currentUser = SecurityUtil.getCurrentUser();
        return ApiResponse.ofSuccess(currentUser);
    }
}
